package com.shuran.handler;

import com.server.protobuf.ImModel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.stereotype.Component;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description : function description
 * ---------------------------------
 * @Author : deane
 * @Date : Create in 2020/5/31 19:02
 * <p>
 * Copyright (C)2013-2020 小树盛凯科技 All rights reserved.
 */
@Component
@ChannelHandler.Sharable
public class HeartHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            switch (event.state()) {
                case ALL_IDLE:
                    type = "all idle";
                    break;
                case READER_IDLE:
                    type = "read idle";
                    break;
                case WRITER_IDLE:
                    type = "write idle";
                    break;
                default:
                    break;
            }
            System.out.println(ctx.channel().remoteAddress() + "超时类型：" + type);
        }
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ImModel.Command command = (ImModel.Command) msg;

        if (command.getType().equals(ImModel.Type.PING)) {
            System.out.println("接收到客户端" + ctx.channel().remoteAddress() + " :PING消息");
        }
        ctx.writeAndFlush(crreatePongMessage(":PONG"));
        if (ctx.channel().isOpen()) {
            ctx.fireChannelRead(msg);
        }
    }

    private ImModel.Command crreatePongMessage(String content) {
        ImModel.Command.Builder command = ImModel.Command.newBuilder();
        command.setId(13732);
        command.setCid("test");
        command.setType(ImModel.Type.PONG);
        command.setContent(content);
        return command.build();
    }
}
